package com.kanshu.ksgb.fastread.doudou.module.login.thirdlogin;

import android.content.Context;

import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.view.LoadingDialog;
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent;
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.BindInfo;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.wxapi.WXEntryActivity;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by wcy on 2017\6\28 0028.
 */

public class WxLogin {
    private static long sClickTime;
    private Context mContext;
    LoadingDialog mLoadingDialog;
    public static void login(Context context) {
        if (UserUtils.isLogin()) {
            return;
        }
        if (System.currentTimeMillis() - sClickTime < 500) {
            return;
        }
        sClickTime = System.currentTimeMillis();
        WXEntryActivity.WX_TYPE = WXEntryActivity.TYPE_OTHER;
        new WxLogin(context).startLogin();
    }
    public WxLogin(Context context) {
        mContext = context;
        EventBus.getDefault().register(this);
    }
    private void startLogin() {
        mLoadingDialog = new LoadingDialog(mContext, "正在加载中");
        mLoadingDialog.show();
        IWXAPI api = WXAPIFactory.createWXAPI(mContext,WXEntryActivity.getWxAppID(mContext));
        api.registerApp(WXEntryActivity.getWxAppID(mContext));
        if (api.isWXAppInstalled()) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = mContext.getPackageName();
            api.sendReq(req);
        } else {
            mLoadingDialog.dismiss();
            ToastUtil.showMessage(mContext, "请安装微信客户端");

        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void handleBindEvent(BindEvent event) {
        mLoadingDialog.dismiss();
        EventBus.getDefault().unregister(this);
    }

    public static void bindWithdraw(Context context) {
        if (System.currentTimeMillis() - sClickTime < 500) {
            return;
        }
        sClickTime = System.currentTimeMillis();
        WXEntryActivity.WX_TYPE = WXEntryActivity.TYPE_BIND_WITHDRAW;
        new WxLogin(context).startLogin();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void handleBindEvent(BindInfo event) {
        mLoadingDialog.dismiss();
        EventBus.getDefault().unregister(this);
    }
}
